//
//  CardCommentViewController.m
//  jiyujiaProgram
//
//  Created by Jame on 15/12/17.
//  Copyright © 2015年 中良 赵. All rights reserved.
//

#import "CardCommentViewController.h"
#import "CardDetailCell.h"
#import "CardCommentCell.h"
#import "CardCommentModel.h"

@interface CardCommentViewController () <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIAlertViewDelegate>

@end

@implementation CardCommentViewController
{
    MemberModel *_memberModel;
    TeacherModel *_teacherModel;

    UITableView *_tableView;
    
    CGRect rect;
    UIView *_commentView;
    UITextField *_textField;
    
    NSMutableArray *_dataArray;
    NSMutableArray *_topArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatNavigationBarWithImage:nil title:self.data.title];
    [self creatNavigationBarLeftItemWithLeftTitle:nil LeftImage:ECIMAGENAME(@"back_button.png")];
    [self creatNavigationBarRightItemWithRightTitle:@"赞" RightImage:nil];
    
    [self creatTableView];
    [self creatCommentView];
}

- (void)viewWillAppear:(BOOL)animated
{
    if (_topArray) {
        [_topArray removeAllObjects];
    }else{
        _topArray = [[NSMutableArray alloc] init];
    }
    
    [_topArray addObject:self.data];
    
    [self loadUserInfo];
    [self creatHttpRequest];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keybordFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [super viewWillAppear:YES];

}

- (void)keybordFrameChange:(NSNotification *)noti
{
    
    NSValue *value = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];//取出来的是NSValue
    [value getValue:&rect];
    [UIView animateWithDuration:0.25 delay:0 options:7 animations:^{
        _commentView.frame = CGRectMake(0, rect.origin.y - _commentView.frame.size.height, _commentView.frame.size.width, _commentView.frame.size.height);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [super viewDidDisappear:YES];
}


- (void)leftBtnClick:(id)leftSender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)rightBtnClick:(id)rightSender
{
    [_textField resignFirstResponder];
    
    NSDictionary *data = @{
                           @"posts_Id":self.data.posts_id,
                           @"by_reviewers":self.data.member_Id,
                           @"reviewers":_memberModel.member_Id,
                           @"status":@"2"
                           };
    
    NSDictionary *param = @{
                            @"data":data,
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(CARDADDCOMMENT) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            if ([result[@"errCode"] integerValue] == 200) {
                SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, self);
            }else{
                SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
            }
        }
    }];

}



- (void)loadUserInfo
{
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    _memberModel = userInfo.memberModel;
    _teacherModel = userInfo.teacherModel;
}


- (void)creatHttpRequest
{
    NSDictionary *param = @{
                            @"posts_id":self.data.posts_id,
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(CARDCOMMENT) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            
            [CardCommentModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"CardCommentData",
                         };
            }];
            
            if (_dataArray) {
                [_dataArray removeAllObjects];
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            CardCommentModel *cardComment = [[CardCommentModel alloc] init];
            cardComment = [CardCommentModel objectWithKeyValues:result];
            [_dataArray addObjectsFromArray:cardComment.data];
            [_tableView reloadData];
        }
    }];
}


- (void)creatTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ECSCREEN_W, ECSCREEN_H - 64 - 49) style:UITableViewStylePlain];
    _tableView.backgroundColor = BG_COLOR;
    [self.view addSubview:_tableView];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.tableFooterView = [[UIView alloc]init];
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CardData *data = _topArray[indexPath.section];
        CGSize labelSize = STRING_SIZE_FONT_HEIGHT(204, data.content, 13.f);
        return  (labelSize.height + 60) > 90?60 + labelSize.height:90;
    }else{
        CardCommentData *data = _dataArray[indexPath.row];
        CGSize labelSize = STRING_SIZE_FONT_HEIGHT(254, data.content, 13.f);
        CGFloat height = labelSize.height + 20 + 16 + 5;
        
        return (height > 60) ?height:60;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return _dataArray.count;
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ECSCREEN_W, 5)];
    view.backgroundColor = BG_COLOR;
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *reuseIdentifier = @"cardDetailCell";
        CardDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (nil == cell) {
            NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"CardDetailCell" owner:nil options:nil];
            for (NSObject *obj in arr) {
                if ([obj isKindOfClass:[CardDetailCell class]]) {
                    cell = (CardDetailCell *)obj;
                    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                        [cell setSeparatorInset:UIEdgeInsetsZero];
                    }
                    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                        [cell setLayoutMargins:UIEdgeInsetsZero];
                    }
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    break;
                }
            }
        }
        [cell setCellWithModel:_topArray WithIndexPath:indexPath isHidden:YES];
        return cell;
    }else{
        static NSString *reuseIdentifier = @"cardCommentCell";
        CardCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (nil == cell) {
            NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"CardCommentCell" owner:nil options:nil];
            for (NSObject *obj in arr) {
                if ([obj isKindOfClass:[CardCommentCell class]]) {
                    cell = (CardCommentCell *)obj;
                    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                        [cell setSeparatorInset:UIEdgeInsetsZero];
                    }
                    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                        [cell setLayoutMargins:UIEdgeInsetsZero];
                    }
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    break;
                }
            }
        }
        [cell setCellWithModel:_dataArray WithIndexPath:indexPath];
        return cell;
    }
}


- (void)creatCommentView
{
    _commentView = [[UIView alloc] initWithFrame:CGRectMake(0, ECSCREEN_H - 49, ECSCREEN_W, 49)];
    _commentView.backgroundColor = NAVC_COLOR;
    _commentView.tag = 1001;
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 7, _commentView.frame.size.width - 70, _commentView.frame.size.height - 14)];
//    self.message = _textField;
    _textField.delegate = self;
    _textField.borderStyle = UITextBorderStyleRoundedRect;
    _textField.placeholder = @"请输入评论";
    _textField.textColor = [UIColor blackColor];
    _textField.font = [UIFont systemFontOfSize:14.f];
    _textField.clearsOnBeginEditing = YES;
    [_commentView addSubview:_textField];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(_commentView.frame.size.width - 60, 7, 50, _commentView.frame.size.height - 14);
    [button setTitle:@"发送" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [button addTarget:self action:@selector(sendCommentClick:) forControlEvents:UIControlEventTouchUpInside];
    [_commentView addSubview:button];
    
    [self.view addSubview:_commentView];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
//{
//    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
//    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
//        return NO;
//    }
//    return  YES;
//}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_textField resignFirstResponder];
}



- (void)sendCommentClick:(UIBarButtonItem *)sender
{
    [_textField resignFirstResponder];
    
    NSDictionary *data = @{
                           @"posts_Id":self.data.posts_id,
                           @"by_reviewers":self.data.member_Id,
                           @"reviewers":_memberModel.member_Id,
                           @"content":_textField.text,
                           @"status":@"1"
                           };
    
    NSDictionary *param = @{
                            @"data":data,
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(CARDADDCOMMENT) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            if ([result[@"errCode"] integerValue] == 200) {
                SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, self);
            }else{
                SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
            }
        }
    }];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self creatHttpRequest];
        _textField.text = @"";
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
